using M13;
using M13.Game.World;
using UnityEngine;

namespace Test
{
    public class MapTextureCreate : MonoBehaviour
    {
        public int seed;
        public int worldSizeLength;

        public WorldBuildConfig config;


        private float _noiseScale;
        private int _noiseOcatves;
        private float _threshold;

        [Header("��ͼ����")]

        public Gradient colGrad;
        Color[] _col;
        Texture2D _tex;

        [Space(10)]
        [SerializeField] private float max;
        [SerializeField] private float min;
        [SerializeField] private int maxNum;

        public void TextureCreate()
        {
            max = 0;
            min = 0;
            maxNum = 0;
            _noiseScale = config.noiseScale;
            _noiseOcatves = config.noiseOcatves;
            _threshold = config.landThreshold;

            _tex = new Texture2D(worldSizeLength, worldSizeLength);
            _col = new Color[_tex.height * _tex.width];
            Renderer rend = GetComponent<MeshRenderer>();
            rend.sharedMaterial.mainTexture = _tex;

            Vector2 org = new Vector2(seed / (Mathf.Sqrt(Mathf.Abs(seed + 0.10516f)) + 0.10516f), -seed / (Mathf.Sqrt(Mathf.Abs(seed + 0.10516f))) + 0.10516f);

            for (int x = 0, i = 0; x < worldSizeLength; x++)
            {
                for (int y = 0; y < worldSizeLength; y++, i++)
                {
                    float a = Noise.GetContinentalShelf(x, y, org, worldSizeLength, _threshold, _noiseScale, _noiseOcatves);
                    maxNum = a == 1 ? maxNum + 1 : maxNum;
                    max = a > max ? a : max;
                    min = a < min ? a : min;
                    
                    _col[i] = colGrad.Evaluate(a);
                }
            }

            _tex.SetPixels(_col);
            _tex.Apply();
            _tex.wrapMode = TextureWrapMode.Repeat;
            _tex.filterMode = FilterMode.Point;

            
        }

    }
}